package com.taotao.manage.service;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Service;

import com.taotao.manage.pojo.ContentCategory;

@Service
public class ContentCategoryService extends BaseService<ContentCategory> {

	public void saveContentCategoryAndParent(ContentCategory contentCategory) {

		contentCategory.setIsParent(false);
		contentCategory.setSortOrder(1);
		contentCategory.setStatus(1);
		super.saveSelective(contentCategory);

		// 更新父节点的isParent属性，isParent为false时，改为true
		ContentCategory parent = super.queryById(contentCategory.getParentId());
		if (!parent.getIsParent()) {
			parent.setIsParent(true);
			super.updateSelective(parent);
		}
	}

	public void deleteContentCategory(Long parentId, Long id) {
		//收集要删除的所有节点及其子节点
		ArrayList<Object> ids = new ArrayList<>();
		//添加要删除的节点
		ids.add(id);
		//找出节点
		findSubAll(ids,id);
		//删除节点
		super.deleteByIds(ids, "id");
		//判断是否存在兄弟节点,不存在则修改父目录状态
		ContentCategory record = new ContentCategory();
		record.setParentId(parentId);
		List<ContentCategory> list = super.queryListByWhere(record);
		if (!CollectionUtils.isEmpty(list)) {
			ContentCategory contentCategory = new ContentCategory();
			contentCategory.setId(parentId);
			contentCategory.setIsParent(false);
			super.updateSelective(contentCategory);
		}
	
	}

	private void findSubAll(ArrayList<Object> ids, Long id) {
		
			ContentCategory record = new ContentCategory();
			record.setParentId(id);
			List<ContentCategory> list = super.queryListByWhere(record);
			if (!CollectionUtils.isEmpty(list)) {
				for (ContentCategory contentCategory : list) {
					if (contentCategory.getIsParent()) {
						findSubAll(ids, contentCategory.getId());
					}
					else {
						ids.add(contentCategory.getId());
					}
				}
			}
		}
		
	}


